// 全局变量

// 添加全局错误处理器，帮助调试
window.addEventListener('error', function(event) {
    console.error('全局错误:', event.error);
    console.error('错误信息:', event.message);
    console.error('发生位置:', event.filename, 'line:', event.lineno, 'col:', event.colno);
    alert('发生JavaScript错误，请检查控制台获取详细信息');
});

// 初始化函数
document.addEventListener('DOMContentLoaded', function() {
    console.log('点火线圈成本计算工具 - 初始化');
    
    // 初始化产品图片上传
    initImageUpload();
    
    // 初始化所有复选框事件
    initCheckboxEvents();
    
    // 初始化计算方式切换
    initToggleSwitches();
    
    // 初始化所有输入框的事件
    initInputEvents();
    
    // 初始化标签页切换
    initTabSwitching();
    
    // 初始化按钮事件
    initButtonEvents();
    
    // 初始化铜线计算功能
    initWireCalculation();
    
    // 初始化运输成本计算
    initTransportationCalculation();
});

// 初始化产品图片上传
function initImageUpload() {
    const productImageInput = document.getElementById('productImage');
    const imagePreview = document.getElementById('imagePreview');
    
    // 辅助函数：添加图片到预览区
    function addImageToPreview(file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const imgContainer = document.createElement('div');
            imgContainer.className = 'preview-item';
            
            const img = document.createElement('img');
            img.src = e.target.result;
            img.alt = '产品图片预览';
            
            // 添加删除按钮
            const deleteButton = document.createElement('button');
            deleteButton.className = 'delete-image';
            deleteButton.innerHTML = '×';
            deleteButton.title = '删除图片';
            deleteButton.onclick = function(e) {
                e.preventDefault();
                imgContainer.remove();
            };
            
            imgContainer.appendChild(img);
            imgContainer.appendChild(deleteButton);
            imagePreview.appendChild(imgContainer);
        };
        reader.readAsDataURL(file);
    }
    
    // 文件上传处理
    if (productImageInput) {
        productImageInput.addEventListener('change', function(event) {
            const files = event.target.files;
            
            if (files && files.length > 0) {
                Array.from(files).forEach(file => {
                    addImageToPreview(file);
                });
            }
        });
    }
    
    // 添加粘贴图片功能
    document.addEventListener('paste', function(event) {
        // 获取剪贴板数据
        const items = (event.clipboardData || event.originalEvent.clipboardData).items;
        
        // 遍历剪贴板项
        for (let i = 0; i < items.length; i++) {
            if (items[i].type.indexOf('image') !== -1) {
                // 获取剪贴板中的文件
                const file = items[i].getAsFile();
                
                if (file) {
                    // 添加到预览
                    addImageToPreview(file);
                    
                    // 阻止默认粘贴行为
                    event.preventDefault();
                    break;
                }
            }
        }
    });
}

// 切换元素显示状态的辅助函数
function toggleElementDisplay(elementId, isVisible) {
    const element = document.getElementById(elementId);
    if (element) {
        element.style.display = isVisible ? 'block' : 'none';
    }
}

// 初始化复选框事件
function initCheckboxEvents() {
    // BOM物料复选框
    const checkboxes = [
        {checkbox: 'copperBasePriceCheck', form: 'copperBasePriceForm'},
        {checkbox: 'customPlasticCheck', form: 'customPlasticForm'},
        {checkbox: 'moduleCheck', form: 'moduleForm'},
        {checkbox: 'ironCoreCheck', form: 'ironCoreForm'},
        {checkbox: 'ironSleeveCheck', form: 'ironSleeveForm'},
        {checkbox: 'magnetCheck', form: 'magnetForm'},
        {checkbox: 'screwCheck', form: 'screwForm'},
        {checkbox: 'nutCheck', form: 'nutForm'},
        {checkbox: 'hvRodCheck', form: 'hvRodForm'},
        {checkbox: 'rubberCheck', form: 'rubberForm'},
        {checkbox: 'siliconePadCheck', form: 'siliconePadForm'},
        {checkbox: 'customPartCheck', form: 'customPartForm'},
        {checkbox: 'customPart2Check', form: 'customPart2Form'},
        {checkbox: 'customPart3Check', form: 'customPart3Form'},
        {checkbox: 'customPart4Check', form: 'customPart4Form'},
        {checkbox: 'bubbleBagCheck', form: 'bubbleBagForm'},
        {checkbox: 'innerBoxCheck', form: 'innerBoxForm'},
        {checkbox: 'outerBoxCheck', form: 'outerBoxForm'}
    ];
    
    checkboxes.forEach(item => {
        const checkbox = document.getElementById(item.checkbox);
        const form = document.getElementById(item.form);
        
        if (checkbox && form) {
            checkbox.addEventListener('change', function() {
                form.style.display = this.checked ? 'block' : 'none';
                
                // 如果取消勾选，清除相关表单的值
                if (!this.checked) {
                    const inputs = form.querySelectorAll('input[type="text"], input[type="number"]');
                    inputs.forEach(input => {
                        input.value = input.type === 'number' ? '0' : '';
                    });
                    
                    // 根据不同的复选框调用相应的计算函数
                    if (item.checkbox === 'customPlasticCheck') {
                        calculatePlasticTotal();
                    } else if (item.checkbox === 'screwCheck' || item.checkbox === 'nutCheck' || item.checkbox === 'customPartCheck') {
                        calculatePartsTotal();
                    } else if (item.checkbox.includes('Box') || item.checkbox === 'bubbleBagCheck') {
                        calculatePackagingTotal();
                    } else if (item.checkbox === 'ironCoreCheck' || item.checkbox === 'ironSleeveCheck' || item.checkbox === 'magnetCheck') {
                        calculateCoreTotal();
                    } else {
                        calculateBomTotal(); // 默认情况
                    }
                }
            });
        }
    });
    
    // 人工成本复选框
    const laborProcesses = [
        {checkbox: 'injectionProcess', form: 'injectionProcessForm'},
        {checkbox: 'highVoltageWindingProcess', form: 'highVoltageWindingProcessForm'},
        {checkbox: 'lowVoltageWindingProcess', form: 'lowVoltageWindingProcessForm'},
        {checkbox: 'tinningProcess', form: 'tinningProcessForm'},
        {checkbox: 'weldingProcess', form: 'weldingProcessForm'},
        {checkbox: 'inspectionProcess', form: 'inspectionProcessForm'},
        {checkbox: 'potProcess', form: 'potProcessForm'},
        {checkbox: 'assemblyProcess', form: 'assemblyProcessForm'},
        {checkbox: 'testingProcess', form: 'testingProcessForm'},
        {checkbox: 'packagingProcess', form: 'packagingProcessForm'},
        {checkbox: 'customProcess1', form: 'customProcess1Form'},
        {checkbox: 'customProcess2', form: 'customProcess2Form'},
        {checkbox: 'customProcess3', form: 'customProcess3Form'},
        {checkbox: 'customProcess4', form: 'customProcess4Form'},
        {checkbox: 'customProcess5', form: 'customProcess5Form'}
    ];
    
    laborProcesses.forEach(item => {
        const checkbox = document.getElementById(item.checkbox);
        const form = document.getElementById(item.form);
        
        if (checkbox && form) {
            checkbox.addEventListener('change', function() {
                form.style.display = this.checked ? 'block' : 'none';
                
                // 如果取消勾选，清除相关表单的值
                if (!this.checked) {
                    const inputs = form.querySelectorAll('input[type="text"], input[type="number"]');
                    inputs.forEach(input => {
                        input.value = input.type === 'number' ? '0' : '';
                    });
                    
                    // 更新人工总成本
                    calculateLaborTotal();
                }
            });
        }
    });
    
    // 配件部分
    document.getElementById('screwCheck').addEventListener('change', function() {
        toggleElementDisplay('screwForm', this.checked);
        calculatePartsTotal();
    });
    
    document.getElementById('nutCheck').addEventListener('change', function() {
        toggleElementDisplay('nutForm', this.checked);
        calculatePartsTotal();
    });
    
    document.getElementById('hvRodCheck').addEventListener('change', function() {
        toggleElementDisplay('hvRodForm', this.checked);
        calculatePartsTotal();
    });
    
    document.getElementById('rubberCheck').addEventListener('change', function() {
        toggleElementDisplay('rubberForm', this.checked);
        calculatePartsTotal();
    });
    
    document.getElementById('siliconePadCheck').addEventListener('change', function() {
        toggleElementDisplay('siliconePadForm', this.checked);
        calculatePartsTotal();
    });
    
    document.getElementById('customPartCheck').addEventListener('change', function() {
        toggleElementDisplay('customPartForm', this.checked);
        calculatePartsTotal();
    });
    
    document.getElementById('customPart2Check').addEventListener('change', function() {
        toggleElementDisplay('customPart2Form', this.checked);
        calculatePartsTotal();
    });
    
    document.getElementById('customPart3Check').addEventListener('change', function() {
        toggleElementDisplay('customPart3Form', this.checked);
        calculatePartsTotal();
    });
    
    document.getElementById('customPart4Check').addEventListener('change', function() {
        toggleElementDisplay('customPart4Form', this.checked);
        calculatePartsTotal();
    });
}

// 初始化计算方式切换
function initToggleSwitches() {
    // 塑料件计算方式切换
    const plasticDetailedMode = document.getElementById('plasticDetailedMode');
    const plasticBulkMode = document.getElementById('plasticBulkMode');
    const plasticDetailedSection = document.getElementById('plasticDetailedSection');
    const plasticBulkSection = document.getElementById('plasticBulkSection');
    
    if (plasticDetailedMode && plasticBulkMode) {
        plasticDetailedMode.addEventListener('change', function() {
            if (this.checked) {
                plasticDetailedSection.style.display = 'flex';
                plasticBulkSection.style.display = 'none';
                calculatePlasticTotal();
            }
        });
        
        plasticBulkMode.addEventListener('change', function() {
            if (this.checked) {
                plasticDetailedSection.style.display = 'none';
                plasticBulkSection.style.display = 'block';
                calculatePlasticTotal();
            }
        });
    }
    
    // 人工成本计算方式切换
    const laborDetailedMode = document.getElementById('laborDetailedMode');
    const laborBulkMode = document.getElementById('laborBulkMode');
    const laborDetailedSection = document.getElementById('laborDetailedSection');
    const laborBulkSection = document.getElementById('laborBulkSection');
    
    if (laborDetailedMode && laborBulkMode) {
        laborDetailedMode.addEventListener('change', function() {
            if (this.checked) {
                laborDetailedSection.style.display = 'block';
                laborBulkSection.style.display = 'none';
                calculateLaborTotal();
            }
        });
        
        laborBulkMode.addEventListener('change', function() {
            if (this.checked) {
                laborDetailedSection.style.display = 'none';
                laborBulkSection.style.display = 'block';
                calculateLaborTotal();
            }
        });
    }
        
    // 运输成本计算方式切换
    const transportDetailedMode = document.getElementById('transportDetailedMode');
    const transportBulkMode = document.getElementById('transportBulkMode');
    const transportDetailedSection = document.getElementById('transportDetailedSection');
    const transportBulkSection = document.getElementById('transportBulkSection');
    
    if (transportDetailedMode && transportBulkMode) {
        transportDetailedMode.addEventListener('change', function() {
            if (this.checked) {
                transportDetailedSection.style.display = 'block';
                transportBulkSection.style.display = 'none';
                calculateShippingFee(); // 触发运费计算
            }
        });
        
        transportBulkMode.addEventListener('change', function() {
            if (this.checked) {
                transportDetailedSection.style.display = 'none';
                transportBulkSection.style.display = 'block';
                calculateTransportationTotal(); // 直接使用输入的运输成本
            }
        });
    }
}

// 初始化输入框事件
function initInputEvents() {
    // 塑料件计算
    attachInputEvents('outerShellWeight', 'outerShellUnitPrice', 'outerShellCost', 'outerShellCostDisplay', calculatePlasticTotal);
    attachInputEvents('highVoltageWeight', 'highVoltageUnitPrice', 'highVoltageCost', 'highVoltageCostDisplay', calculatePlasticTotal);
    attachInputEvents('lowVoltageWeight', 'lowVoltageUnitPrice', 'lowVoltageCost', 'lowVoltageCostDisplay', calculatePlasticTotal);
    attachInputEvents('customPlasticWeight', 'customPlasticUnitPrice', 'customPlasticCost', 'customPlasticCostDisplay', calculatePlasticTotal);
    
    // 整体采购塑料件
    const plasticBulkPrice = document.getElementById('plasticBulkPrice');
    if (plasticBulkPrice) {
        plasticBulkPrice.addEventListener('input', calculatePlasticTotal);
    }
    
    // 铜线计算相关函数
    initWireCalculation();
    
    // 铁芯计算
    attachInputEvents('coreWeight', 'coreUnitPrice', 'coreTotal', 'coreTotalDisplay', calculateBomTotal);
    
    // 整体采购铁芯
    const coreBulkPrice = document.getElementById('coreBulkPrice');
    if (coreBulkPrice) {
        coreBulkPrice.addEventListener('input', calculateCoreTotal);
    }
    
    // 配件计算
    attachQuantityPriceEvents('screwQuantity', 'screwUnitPrice', 'screwCost', 'screwCostDisplay', calculatePartsTotal);
    attachQuantityPriceEvents('nutQuantity', 'nutUnitPrice', 'nutCost', 'nutCostDisplay', calculatePartsTotal);
    attachQuantityPriceEvents('hvRodQuantity', 'hvRodUnitPrice', 'hvRodCost', 'hvRodCostDisplay', calculatePartsTotal);
    attachQuantityPriceEvents('rubberQuantity', 'rubberUnitPrice', 'rubberCost', 'rubberCostDisplay', calculatePartsTotal);
    attachQuantityPriceEvents('siliconePadQuantity', 'siliconePadUnitPrice', 'siliconePadCost', 'siliconePadCostDisplay', calculatePartsTotal);
    attachQuantityPriceEvents('customPartQuantity', 'customPartUnitPrice', 'customPartCost', 'customPartCostDisplay', calculatePartsTotal);
    attachQuantityPriceEvents('customPart2Quantity', 'customPart2UnitPrice', 'customPart2Cost', 'customPart2CostDisplay', calculatePartsTotal);
    attachQuantityPriceEvents('customPart3Quantity', 'customPart3UnitPrice', 'customPart3Cost', 'customPart3CostDisplay', calculatePartsTotal);
    attachQuantityPriceEvents('customPart4Quantity', 'customPart4UnitPrice', 'customPart4Cost', 'customPart4CostDisplay', calculatePartsTotal);
    
    // 环氧树脂计算
    const resinWeightInput = document.getElementById('resinWeight');
    const resinPriceInput = document.getElementById('resinUnitPrice');
    
    if (resinWeightInput && resinPriceInput) {
        const updateResinCost = function() {
            const resinTotal = calculateResinTotal();
            // 计算完成后更新BOM总成本
            calculateBomTotal();
        };
        
        resinWeightInput.addEventListener('input', updateResinCost);
        resinPriceInput.addEventListener('input', updateResinCost);
    }
    
    // 包装计算
    const packagingInputs = ['bubbleBagPrice', 'innerBoxPrice', 'outerBoxPrice', 'quantityPerBox'];
    packagingInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', calculatePackagingTotal);
        }
    });
    
    // 模块计算
    const moduleInputs = ['modulePrice', 'moduleSpec'];
    moduleInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', function() {
                if (document.getElementById('moduleCheck').checked) {
                    calculateModuleTotal();
                }
            });
        }
    });
    
    // 人工成本计算
    const laborInputs = [
        'injectionHours', 'highVoltageWindingHours', 'lowVoltageWindingHours',
        'tinningHours', 'weldingHours', 'inspectionHours', 'potHours',
        'assemblyHours', 'testingHours', 'packagingHours',
        'customProcess1Hours', 'customProcess2Hours', 'customProcess3Hours',
        'customProcess4Hours', 'customProcess5Hours', 'hourlyRate'
    ];
    
    laborInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', calculateLaborTotal);
        }
    });
    
    // 监听人工整体输入成本
    const laborBulkPrice = document.getElementById('laborBulkPrice');
    if (laborBulkPrice) {
        laborBulkPrice.addEventListener('input', calculateLaborTotal);
    }
    
    // 监听自定义工序名称输入
    const customProcessNames = [
        'customProcess1Name', 'customProcess2Name', 'customProcess3Name',
        'customProcess4Name', 'customProcess5Name'
    ];
    
    customProcessNames.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', function() {
                // 当名称变化时不需要重新计算，但可以在这里添加其他逻辑
            });
        }
    });
    
    // 铁芯相关输入字段绑定事件
    document.getElementById('ironCorePrice').addEventListener('input', function() {
        if (document.getElementById('ironCoreCheck').checked) {
            calculateCoreTotal();
        }
    });
    
    document.getElementById('ironSleevePrice').addEventListener('input', function() {
        if (document.getElementById('ironSleeveCheck').checked) {
            calculateCoreTotal();
        }
    });
    
    document.getElementById('magnetPrice').addEventListener('input', function() {
        if (document.getElementById('magnetCheck').checked) {
            calculateCoreTotal();
        }
    });
    
    // 塑料件相关输入字段绑定事件
    // 塑料件整体采购模式下的规格/供应商输入监听
    const plasticBulkSpec = document.getElementById('plasticBulkSpec');
    if (plasticBulkSpec) {
        plasticBulkSpec.addEventListener('input', function() {
            // 只有在整体采购模式下才执行
            if (!document.getElementById('plasticDetailedMode').checked) {
                calculatePlasticTotal();
            }
        });
    }
    
    // 塑料件整体采购价格监听
    const plasticBulkPriceInput = document.getElementById('plasticBulkPrice');
    if (plasticBulkPriceInput) {
        plasticBulkPriceInput.addEventListener('input', function() {
            // 只有在整体采购模式下才执行
            if (!document.getElementById('plasticDetailedMode').checked) {
                calculatePlasticTotal();
            }
        });
    }
    
    // 模块计算
    document.getElementById('modulePrice').addEventListener('input', function() {
        if (document.getElementById('moduleCheck').checked) {
            calculateModuleTotal();
        }
    });
    
    document.getElementById('moduleSpec').addEventListener('input', function() {
        // 规格改变不影响价格，但需要记录用于生成BOM明细
    });
}

// 为重量和单价输入框添加事件监听
function attachInputEvents(weightId, priceId, costId, displayId, callbackFn) {
    const weightInput = document.getElementById(weightId);
    const priceInput = document.getElementById(priceId);
    const costInput = document.getElementById(costId);
    const costDisplay = document.getElementById(displayId);
    
    if (weightInput && priceInput && costInput && costDisplay) {
        const calculateCost = function() {
            const weight = parseFloat(weightInput.value) || 0;
            const price = parseFloat(priceInput.value) || 0;
            // 单位已经是¥/kg，所以不需要再除以1000
            const cost = weight * (price / 1000);
            
            costInput.value = cost.toFixed(2);
            costDisplay.textContent = cost.toFixed(2) + ' ¥';
            
            // 执行回调函数，更新总成本
            if (typeof callbackFn === 'function') {
                callbackFn();
            }
            
            // 添加闪烁效果
            animateValueChange(displayId);
        };
        
        weightInput.addEventListener('input', calculateCost);
        priceInput.addEventListener('input', calculateCost);
    }
}

// 为数量和单价输入框添加事件监听
function attachQuantityPriceEvents(quantityId, priceId, costId, displayId, callbackFn) {
    const quantityInput = document.getElementById(quantityId);
    const priceInput = document.getElementById(priceId);
    const costInput = document.getElementById(costId);
    const costDisplay = document.getElementById(displayId);
    
    if (quantityInput && priceInput && costInput && costDisplay) {
        const calculateCost = function() {
            const quantity = parseFloat(quantityInput.value) || 0;
            const price = parseFloat(priceInput.value) || 0;
            const cost = quantity * price;
            
            costInput.value = cost.toFixed(2);
            costDisplay.textContent = cost.toFixed(2) + ' ¥';
            
            // 执行回调函数，更新总成本
            if (typeof callbackFn === 'function') {
                callbackFn();
            }
            
            // 添加闪烁效果
            animateValueChange(displayId);
        };
        
        quantityInput.addEventListener('input', calculateCost);
        priceInput.addEventListener('input', calculateCost);
    }
}

// 初始化标签页切换
function initTabSwitching() {
    const tabButtons = document.querySelectorAll('.tab-button');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 获取当前标签页
            const tabId = this.getAttribute('data-tab');
            
            // 移除所有标签按钮的激活状态
            tabButtons.forEach(btn => {
                btn.classList.remove('active');
            });
            
            // 隐藏所有标签内容
            const tabPanes = document.querySelectorAll('.tab-pane');
            tabPanes.forEach(pane => {
                pane.classList.remove('active');
            });
            
            // 激活当前标签按钮和内容
            this.classList.add('active');
            document.getElementById(tabId).classList.add('active');
        });
    });
}

// 初始化按钮事件
function initButtonEvents() {
    // 计算按钮
    const calculateButton = document.getElementById('calculateButton');
    if (calculateButton) {
        calculateButton.addEventListener('click', function() {
            calculateTotalCost();
            generateCostDetail();
            
            // 显示成本明细区域
            const costDetail = document.getElementById('costDetail');
            if (costDetail) {
                costDetail.style.display = 'block';
            }
        });
    }
    
    // 导出Excel按钮
    const exportExcelButton = document.getElementById('exportExcelButton');
    if (exportExcelButton) {
        exportExcelButton.addEventListener('click', exportToExcel);
    }
    
    // 重置按钮
    const resetButton = document.getElementById('resetButton');
    if (resetButton) {
        resetButton.addEventListener('click', resetForm);
    }
}

// 添加值变化的动画效果
function animateValueChange(elementId) {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error('无法找到元素:', elementId);
        return;
    }
    
    // 添加闪烁动画
    element.style.transition = 'all 0.3s';
    element.style.backgroundColor = '#b2dfdb';
    element.style.color = '#00695c';
    element.style.fontWeight = 'bold';
    
    // 动画结束后恢复
    setTimeout(() => {
        element.style.backgroundColor = '';
        element.style.color = '#1cad80';
        element.style.fontWeight = '500';
    }, 1000);
}

// 计算塑料件总成本
function calculatePlasticTotal() {
    let total = 0;
    
    // 检查计算方式
    if (document.getElementById('plasticDetailedMode').checked) {
        // 分项计算方式
        // 外壳
        if (document.getElementById('outerShellCheck').checked) {
            total += parseFloat(document.getElementById('outerShellCost').value) || 0;
        }
        
        // 高压骨架
        if (document.getElementById('highVoltageCheck').checked) {
            total += parseFloat(document.getElementById('highVoltageCost').value) || 0;
        }
        
        // 低压骨架
        if (document.getElementById('lowVoltageCheck').checked) {
            total += parseFloat(document.getElementById('lowVoltageCost').value) || 0;
        }
        
        // 自定义配件
        if (document.getElementById('customPlasticCheck').checked) {
            total += parseFloat(document.getElementById('customPlasticCost').value) || 0;
        }
    } else {
        // 整体采购方式
        total = parseFloat(document.getElementById('plasticBulkPrice').value) || 0;
    }
    
    // 更新塑料件总成本
    document.getElementById('plasticTotal').value = total.toFixed(2);
    document.getElementById('plasticTotalDisplay').textContent = total.toFixed(2) + ' ¥';
    
    // 更新BOM总成本
    calculateBomTotal();
    
    // 添加闪烁效果
    animateValueChange('plasticTotalDisplay');
}

// 计算铜线总成本
function calculateWireTotal() {
    const wireTotalInput = document.getElementById('wireTotal');
    const wireTotalDisplay = document.getElementById('wireTotalDisplay');
    
    let totalCost = 0;
    
    // 分项计算模式
    const highVoltageCheck = document.getElementById('highVoltageWireCheck');
    const lowVoltageCheck = document.getElementById('lowVoltageWireCheck');
    
    if (highVoltageCheck && highVoltageCheck.checked) {
        totalCost += parseFloat(document.getElementById('highVoltageWireCost').value) || 0;
    }
    
    if (lowVoltageCheck && lowVoltageCheck.checked) {
        totalCost += parseFloat(document.getElementById('lowVoltageWireCost').value) || 0;
    }
    
    wireTotalInput.value = totalCost.toFixed(2);
    wireTotalDisplay.textContent = formatCurrency(totalCost);
    
    // 更新BOM总成本
    calculateBomTotal();
    
    // 高亮显示更新的字段
    animateValueChange('wireTotalDisplay');
}

// 计算铁芯总成本
function calculateCoreTotal() {
    let total = 0;
    
    // 铁芯卡片
    if (document.getElementById('ironCoreCheck').checked) {
        const ironCorePrice = parseFloat(document.getElementById('ironCorePrice').value) || 0;
        document.getElementById('ironCoreCost').value = ironCorePrice.toFixed(2);
        document.getElementById('ironCoreCostDisplay').textContent = ironCorePrice.toFixed(2) + ' ¥';
        total += ironCorePrice;
        
        // 添加闪烁效果
        animateValueChange('ironCoreCostDisplay');
    }
    
    // 铁套卡片
    if (document.getElementById('ironSleeveCheck').checked) {
        const ironSleevePrice = parseFloat(document.getElementById('ironSleevePrice').value) || 0;
        document.getElementById('ironSleeveCost').value = ironSleevePrice.toFixed(2);
        document.getElementById('ironSleeveCostDisplay').textContent = ironSleevePrice.toFixed(2) + ' ¥';
        total += ironSleevePrice;
        
        // 添加闪烁效果
        animateValueChange('ironSleeveCostDisplay');
    }
    
    // 磁铁卡片
    if (document.getElementById('magnetCheck').checked) {
        const magnetPrice = parseFloat(document.getElementById('magnetPrice').value) || 0;
        document.getElementById('magnetCost').value = magnetPrice.toFixed(2);
        document.getElementById('magnetCostDisplay').textContent = magnetPrice.toFixed(2) + ' ¥';
        total += magnetPrice;
        
        // 添加闪烁效果
        animateValueChange('magnetCostDisplay');
    }
    
    // 更新铁芯总成本
    document.getElementById('coreTotal').value = total.toFixed(2);
    document.getElementById('coreTotalDisplay').textContent = total.toFixed(2) + ' ¥';
    
    // 更新BOM总成本
    calculateBomTotal();
    
    // 添加闪烁效果
    animateValueChange('coreTotalDisplay');
}

// 计算配件总成本
function calculatePartsTotal() {
    let total = 0;
    
    // 检查螺丝是否启用
    if (document.getElementById('screwCheck').checked) {
        const quantity = parseInt(document.getElementById('screwQuantity').value) || 0;
        const unitPrice = parseFloat(document.getElementById('screwUnitPrice').value) || 0;
        const cost = quantity * unitPrice;
        
        document.getElementById('screwCost').value = cost.toFixed(2);
        document.getElementById('screwCostDisplay').textContent = cost.toFixed(2) + ' ¥';
        
        total += cost;
    }
    
    // 检查螺帽是否启用
    if (document.getElementById('nutCheck').checked) {
        const quantity = parseInt(document.getElementById('nutQuantity').value) || 0;
        const unitPrice = parseFloat(document.getElementById('nutUnitPrice').value) || 0;
        const cost = quantity * unitPrice;
        
        document.getElementById('nutCost').value = cost.toFixed(2);
        document.getElementById('nutCostDisplay').textContent = cost.toFixed(2) + ' ¥';
        
        total += cost;
    }
    
    // 检查高压杆是否启用
    if (document.getElementById('hvRodCheck').checked) {
        const quantity = parseInt(document.getElementById('hvRodQuantity').value) || 0;
        const unitPrice = parseFloat(document.getElementById('hvRodUnitPrice').value) || 0;
        const cost = quantity * unitPrice;
        
        document.getElementById('hvRodCost').value = cost.toFixed(2);
        document.getElementById('hvRodCostDisplay').textContent = cost.toFixed(2) + ' ¥';
        
        total += cost;
    }
    
    // 检查橡胶件是否启用
    if (document.getElementById('rubberCheck').checked) {
        const quantity = parseInt(document.getElementById('rubberQuantity').value) || 0;
        const unitPrice = parseFloat(document.getElementById('rubberUnitPrice').value) || 0;
        const cost = quantity * unitPrice;
        
        document.getElementById('rubberCost').value = cost.toFixed(2);
        document.getElementById('rubberCostDisplay').textContent = cost.toFixed(2) + ' ¥';
        
        total += cost;
    }
    
    // 检查硅胶垫片是否启用
    if (document.getElementById('siliconePadCheck').checked) {
        const quantity = parseInt(document.getElementById('siliconePadQuantity').value) || 0;
        const unitPrice = parseFloat(document.getElementById('siliconePadUnitPrice').value) || 0;
        const cost = quantity * unitPrice;
        
        document.getElementById('siliconePadCost').value = cost.toFixed(3);
        document.getElementById('siliconePadCostDisplay').textContent = cost.toFixed(2) + ' ¥';
        
        total += cost;
    }
    
    // 检查自定义配件是否启用
    if (document.getElementById('customPartCheck').checked) {
        const quantity = parseInt(document.getElementById('customPartQuantity').value) || 0;
        const unitPrice = parseFloat(document.getElementById('customPartUnitPrice').value) || 0;
        const cost = quantity * unitPrice;
        
        document.getElementById('customPartCost').value = cost.toFixed(2);
        document.getElementById('customPartCostDisplay').textContent = cost.toFixed(2) + ' ¥';
        
        total += cost;
    }
    
    // 检查自定义配件2是否启用
    if (document.getElementById('customPart2Check').checked) {
        const quantity = parseInt(document.getElementById('customPart2Quantity').value) || 0;
        const unitPrice = parseFloat(document.getElementById('customPart2UnitPrice').value) || 0;
        const cost = quantity * unitPrice;
        
        document.getElementById('customPart2Cost').value = cost.toFixed(2);
        document.getElementById('customPart2CostDisplay').textContent = cost.toFixed(2) + ' ¥';
        
        total += cost;
    }
    
    // 检查自定义配件3是否启用
    if (document.getElementById('customPart3Check').checked) {
        const quantity = parseInt(document.getElementById('customPart3Quantity').value) || 0;
        const unitPrice = parseFloat(document.getElementById('customPart3UnitPrice').value) || 0;
        const cost = quantity * unitPrice;
        
        document.getElementById('customPart3Cost').value = cost.toFixed(2);
        document.getElementById('customPart3CostDisplay').textContent = cost.toFixed(2) + ' ¥';
        
        total += cost;
    }
    
    // 检查自定义配件4是否启用
    if (document.getElementById('customPart4Check').checked) {
        const quantity = parseInt(document.getElementById('customPart4Quantity').value) || 0;
        const unitPrice = parseFloat(document.getElementById('customPart4UnitPrice').value) || 0;
        const cost = quantity * unitPrice;
        
        document.getElementById('customPart4Cost').value = cost.toFixed(2);
        document.getElementById('customPart4CostDisplay').textContent = cost.toFixed(2) + ' ¥';
        
        total += cost;
    }
    
    // 更新配件总成本
    document.getElementById('partsTotal').value = total.toFixed(2);
    document.getElementById('partsTotalDisplay').textContent = total.toFixed(2) + ' ¥';
    
    // 更新BOM总成本
    calculateBomTotal();
    
    // 添加闪烁效果
    animateValueChange('partsTotalDisplay');
}

// 计算环氧树脂总成本
function calculateResinTotal() {
    const weight = parseFloat(document.getElementById('resinWeight').value) || 0;
    const price = parseFloat(document.getElementById('resinUnitPrice').value) || 0;
    // 单位已经是¥/kg，所以不需要再除以1000
    const total = weight * (price / 1000);
    
    // 更新环氧树脂总成本
    document.getElementById('resinTotal').value = total.toFixed(2);
    document.getElementById('resinTotalDisplay').textContent = total.toFixed(2) + ' ¥';
    
    // 添加闪烁效果
    animateValueChange('resinTotalDisplay');
    
    // 在函数末尾加上对calculateBomTotal的调用
    return total;
}

// 计算包装总成本
function calculatePackagingTotal() {
    let total = 0;
    
    // 气泡袋
    if (document.getElementById('bubbleBagCheck').checked) {
        total += parseFloat(document.getElementById('bubbleBagPrice').value) || 0;
        
        // 更新气泡袋成本显示
        document.getElementById('bubbleBagCost').value = parseFloat(document.getElementById('bubbleBagPrice').value) || 0;
        document.getElementById('bubbleBagCostDisplay').textContent = (parseFloat(document.getElementById('bubbleBagPrice').value) || 0).toFixed(2) + ' ¥';
    }
    
    // 内盒
    if (document.getElementById('innerBoxCheck').checked) {
        total += parseFloat(document.getElementById('innerBoxPrice').value) || 0;
        
        // 更新内盒成本显示
        document.getElementById('innerBoxCost').value = parseFloat(document.getElementById('innerBoxPrice').value) || 0;
        document.getElementById('innerBoxCostDisplay').textContent = (parseFloat(document.getElementById('innerBoxPrice').value) || 0).toFixed(2) + ' ¥';
    }
    
    // 外箱
    if (document.getElementById('outerBoxCheck').checked) {
        const boxPrice = parseFloat(document.getElementById('outerBoxPrice').value) || 0;
        const quantityPerBox = parseFloat(document.getElementById('quantityPerBox').value) || 1;
        const boxCost = boxPrice / Math.max(1, quantityPerBox); // 避免除以零
        
        total += boxCost;
        
        // 更新外箱成本显示
        document.getElementById('outerBoxCost').value = boxCost.toFixed(2);
        document.getElementById('outerBoxCostDisplay').textContent = boxCost.toFixed(2) + ' ¥';
        
        // 添加闪烁效果
        animateValueChange('outerBoxCostDisplay');
    }
    
    // 更新包装总成本
    document.getElementById('packagingTotal').value = total.toFixed(2);
    document.getElementById('packagingTotalDisplay').textContent = total.toFixed(2) + ' ¥';
    
    // 更新BOM总成本
    calculateBomTotal();
    
    // 添加闪烁效果
    animateValueChange('packagingTotalDisplay');
}

// 计算模块总成本
function calculateModuleTotal() {
    let total = 0;
    
    // 计算点火模块成本
    if (document.getElementById('moduleCheck').checked) {
        const modulePrice = parseFloat(document.getElementById('modulePrice').value) || 0;
        document.getElementById('moduleCost').value = modulePrice.toFixed(2);
        document.getElementById('moduleCostDisplay').textContent = modulePrice.toFixed(2) + ' ¥';
        total = modulePrice;
    }
    
    // 更新模块总成本
    document.getElementById('moduleTotal').value = total.toFixed(2);
    document.getElementById('moduleTotalDisplay').textContent = total.toFixed(2) + ' ¥';
    
    // 更新BOM总成本
    calculateBomTotal();
    
    // 添加闪烁效果
    animateValueChange('moduleTotalDisplay');
}

// 计算运输成本
function calculateTransportationTotal() {
    if (document.getElementById('transportBulkMode').checked) {
        // 直接输入模式 - 此模式下直接输入的就是单个产品的运输成本
    const transportationCost = parseFloat(document.getElementById('transportationCost').value) || 0;
    
    // 更新运输成本
    document.getElementById('transportationTotal').value = transportationCost.toFixed(2);
    document.getElementById('transportationTotalDisplay').textContent = transportationCost.toFixed(2) + ' ¥';
    
    // 更新总成本
    calculateTotalCost();
    
    // 添加闪烁效果
    animateValueChange('transportationTotalDisplay');
    } else {
        // 自动计算模式下，由calculateShippingFee函数处理
        calculateShippingFee();
    }
}

// 计算BOM总成本
function calculateBomTotal() {
    const plasticTotal = parseFloat(document.getElementById('plasticTotal').value) || 0;
    const wireTotal = parseFloat(document.getElementById('wireTotal').value) || 0;
    const coreTotal = parseFloat(document.getElementById('coreTotal').value) || 0;
    const moduleTotal = parseFloat(document.getElementById('moduleTotal').value) || 0;
    const partsTotal = parseFloat(document.getElementById('partsTotal').value) || 0;
    const resinTotal = parseFloat(document.getElementById('resinTotal').value) || 0;
    const packagingTotal = parseFloat(document.getElementById('packagingTotal').value) || 0;
    
    const total = plasticTotal + wireTotal + coreTotal + moduleTotal + partsTotal + resinTotal + packagingTotal;
    
    // 更新BOM总成本
    document.getElementById('bomTotal').value = total.toFixed(2);
    document.getElementById('bomTotalDisplay').textContent = total.toFixed(2) + ' ¥';
    
    // 更新总成本
    calculateTotalCost();
    
    // 添加闪烁效果
    animateValueChange('bomTotalDisplay');
}

// 计算人工总成本
function calculateLaborTotal() {
    let total = 0;
    
    // 检查计算方式
    if (document.getElementById('laborDetailedMode').checked) {
        // 分项计算方式 - 使用新的计算公式
        const hourlyRate = parseFloat(document.getElementById('hourlyRate').value) || 0;
        
        if (hourlyRate > 0) {
            // 汇总所有工序工时
            const laborProcesses = [
                {check: 'injectionProcess', hours: 'injectionHours', label: '注塑'},
                {check: 'highVoltageWindingProcess', hours: 'highVoltageWindingHours', label: '高压绕线'},
                {check: 'lowVoltageWindingProcess', hours: 'lowVoltageWindingHours', label: '低压绕线'},
                {check: 'tinningProcess', hours: 'tinningHours', label: '上锡'},
                {check: 'weldingProcess', hours: 'weldingHours', label: '焊接'},
                {check: 'inspectionProcess', hours: 'inspectionHours', label: '检测'},
                {check: 'potProcess', hours: 'potHours', label: '灌胶'},
                {check: 'assemblyProcess', hours: 'assemblyHours', label: '组装'},
                {check: 'testingProcess', hours: 'testingHours', label: '测试'},
                {check: 'packagingProcess', hours: 'packagingHours', label: '包装'}
            ];
            
            let totalHours = 0;
            laborProcesses.forEach(process => {
                if (document.getElementById(process.check).checked) {
                    totalHours += parseFloat(document.getElementById(process.hours).value) || 0;
                }
            });
            
            // 添加自定义工序工时
            for (let i = 1; i <= 5; i++) {
                const checkId = `customProcess${i}`;
                const hoursId = `customProcess${i}Hours`;
                
                if (document.getElementById(checkId).checked) {
                    totalHours += parseFloat(document.getElementById(hoursId).value) || 0;
                }
            }
            
            // 计算单个产品人工成本 = 总工时 × 大工工价 ÷ 1000
            total = (totalHours * hourlyRate) / 1000;
        }
    } else {
        // 整体输入方式
        total = parseFloat(document.getElementById('laborBulkPrice').value) || 0;
    }
    
    // 更新人工总成本
    document.getElementById('laborTotal').value = total.toFixed(2);
    document.getElementById('laborTotalDisplay').textContent = total.toFixed(2) + ' ¥';
    
    // 更新总成本
    calculateTotalCost();
    
    // 添加闪烁效果
    animateValueChange('laborTotalDisplay');
}

// 计算水电费及设备折旧费总成本
function calculateUtilitiesAndDepreciationTotal() {
    const utilitiesAndDepreciation = parseFloat(document.getElementById('utilitiesAndDepreciation').value) || 0;
    
    // 更新水电费及设备折旧费总成本
    document.getElementById('utilitiesAndDepreciationTotal').value = utilitiesAndDepreciation.toFixed(2);
    document.getElementById('utilitiesAndDepreciationTotalDisplay').textContent = utilitiesAndDepreciation.toFixed(2) + ' ¥';
    
    // 更新总成本
    calculateTotalCost();
    
    // 添加闪烁效果
    animateValueChange('utilitiesAndDepreciationTotalDisplay');
}

// 计算管理费总成本
function calculateManagementTotal() {
    const managementCost = parseFloat(document.getElementById('managementCost').value) || 0;
    
    // 更新管理费总成本
    document.getElementById('managementTotal').value = managementCost.toFixed(2);
    document.getElementById('managementTotalDisplay').textContent = managementCost.toFixed(2) + ' ¥';
    
    // 更新总成本
    calculateTotalCost();
    
    // 添加闪烁效果
    animateValueChange('managementTotalDisplay');
}

// 计算总成本
function calculateTotalCost() {
    const bomTotal = parseFloat(document.getElementById('bomTotal').value) || 0;
    const laborTotal = parseFloat(document.getElementById('laborTotal').value) || 0;
    const managementTotal = parseFloat(document.getElementById('managementTotal').value) || 0;
    const transportationTotal = parseFloat(document.getElementById('transportationTotal').value) || 0;
    const utilitiesAndDepreciationTotal = parseFloat(document.getElementById('utilitiesAndDepreciationTotal').value) || 0;
    
    const totalCost = bomTotal + laborTotal + managementTotal + transportationTotal + utilitiesAndDepreciationTotal;
    
    // 更新总成本显示
    document.getElementById('totalCost').value = totalCost.toFixed(2);
    document.getElementById('totalCostDisplay').textContent = totalCost.toFixed(2) + ' ¥';
    
    // 更新成本汇总
    document.getElementById('bomTotalSummary').textContent = bomTotal.toFixed(2) + ' ¥';
    document.getElementById('laborTotalSummary').textContent = laborTotal.toFixed(2) + ' ¥';
    document.getElementById('managementTotalSummary').textContent = managementTotal.toFixed(2) + ' ¥';
    document.getElementById('transportationTotalSummary').textContent = transportationTotal.toFixed(2) + ' ¥';
    document.getElementById('utilitiesAndDepreciationTotalSummary').textContent = utilitiesAndDepreciationTotal.toFixed(2) + ' ¥';
    
    // 添加闪烁效果
    animateValueChange('totalCostDisplay');
}

// 生成成本明细
function generateCostDetail() {
    generateCostSummary();
    generateBomDetail();
    generateLaborDetail();
}

// 生成成本汇总明细表格
function generateCostSummary() {
    const tbody = document.getElementById('costSummaryTableBody');
    if (!tbody) return;
    
    // 清空表格
    tbody.innerHTML = '';
    
    const bomTotal = parseFloat(document.getElementById('bomTotal').value) || 0;
    const laborTotal = parseFloat(document.getElementById('laborTotal').value) || 0;
    const managementTotal = parseFloat(document.getElementById('managementTotal').value) || 0;
    const transportationTotal = parseFloat(document.getElementById('transportationTotal').value) || 0;
    const utilitiesAndDepreciationTotal = parseFloat(document.getElementById('utilitiesAndDepreciationTotal').value) || 0;
    const totalCost = parseFloat(document.getElementById('totalCost').value) || 0;
    
    // 添加BOM物料成本行
    addTableRow(tbody, '2. BOM物料成本', bomTotal, totalCost, true);
    
    // 添加BOM细分项
    const bomItems = [
        {label: '塑料件', id: 'plasticTotal'},
        {label: '铜线', id: 'wireTotal'},
        {label: '铁芯', id: 'coreTotal'},
        {label: '模块', id: 'moduleTotal'},
        {label: '配件', id: 'partsTotal'},
        {label: '环氧树脂', id: 'resinTotal'},
        {label: '包装', id: 'packagingTotal'}
    ];
    
    bomItems.forEach(item => {
        const value = parseFloat(document.getElementById(item.id).value) || 0;
        if (value > 0) {
            addTableRow(tbody, '　　' + item.label, value, totalCost, false, true);
        }
    });
    
    // 添加人工成本行
    addTableRow(tbody, '3. 人工成本', laborTotal, totalCost, true);
    
    // 检查人工成本计算方式
    if (document.getElementById('laborDetailedMode').checked) {
        // 分项计算方式，添加人工细分项
        const hourlyRate = parseFloat(document.getElementById('hourlyRate').value) || 0;
        
        // 按照DOM中的实际顺序获取工序（拖拽后的顺序）
        const laborContainer = document.getElementById('laborProcessContainer');
        const draggableCards = laborContainer.querySelectorAll('.draggable-card');
        
        const processMap = {
            'injectionProcess': {check: 'injectionProcess', hours: 'injectionHours', label: '注塑'},
            'highVoltageWindingProcess': {check: 'highVoltageWindingProcess', hours: 'highVoltageWindingHours', label: '高压绕线'},
            'lowVoltageWindingProcess': {check: 'lowVoltageWindingProcess', hours: 'lowVoltageWindingHours', label: '低压绕线'},
            'tinningProcess': {check: 'tinningProcess', hours: 'tinningHours', label: '上锡'},
            'weldingProcess': {check: 'weldingProcess', hours: 'weldingHours', label: '焊接'},
            'inspectionProcess': {check: 'inspectionProcess', hours: 'inspectionHours', label: '检测'},
            'potProcess': {check: 'potProcess', hours: 'potHours', label: '灌胶'},
            'assemblyProcess': {check: 'assemblyProcess', hours: 'assemblyHours', label: '组装'},
            'testingProcess': {check: 'testingProcess', hours: 'testingHours', label: '测试'},
            'packagingProcess': {check: 'packagingProcess', hours: 'packagingHours', label: '包装'}
        };
        
        draggableCards.forEach(card => {
            const processType = card.getAttribute('data-process');
            
            // 处理预定义工序
            if (processMap[processType]) {
                const item = processMap[processType];
                if (document.getElementById(item.check).checked) {
                    const hours = parseFloat(document.getElementById(item.hours).value) || 0;
                    if (hours > 0 && hourlyRate > 0) {
                        const cost = (hours * hourlyRate) / 1000;
                        addTableRow(tbody, '　　' + item.label, cost, totalCost, false, true);
                    }
                }
            }
            // 处理自定义工序
            else if (processType && processType.startsWith('customProcess')) {
                const customIndex = processType.replace('customProcess', '');
                const checkId = `customProcess${customIndex}`;
                const nameId = `customProcess${customIndex}Name`;
                const hoursId = `customProcess${customIndex}Hours`;
                
                if (document.getElementById(checkId).checked) {
                    const customName = document.getElementById(nameId).value || `自定义工序${customIndex}`;
                    const hours = parseFloat(document.getElementById(hoursId).value) || 0;
                    if (hours > 0 && hourlyRate > 0) {
                        const cost = (hours * hourlyRate) / 1000;
                        addTableRow(tbody, '　　' + customName, cost, totalCost, false, true);
                    }
                }
            }
        });
    }
    
    // 添加管理费行
    if (managementTotal > 0) {
        addTableRow(tbody, '4. 管理费', managementTotal, totalCost, true);
    }
    
    // 添加运输成本行
    if (transportationTotal > 0) {
        // 获取运输方式
        let transportLabel = '5. 运输成本';
        
        if (document.getElementById('transportDetailedMode').checked) {
            const destination = document.getElementById('destination').value;
            if (destination) {
                transportLabel = `5. 运输成本（${destination}）`;
                // 添加每个产品运费说明
                transportLabel += '，单件';
            }
        }
        
        addTableRow(tbody, transportLabel, transportationTotal, totalCost, true);
    }
    
    // 添加水电费及设备折旧费行
    if (utilitiesAndDepreciationTotal > 0) {
        addTableRow(tbody, '6. 水电费及设备折旧费', utilitiesAndDepreciationTotal, totalCost, true);
    }
    
    // 添加总计行
    const totalRow = document.createElement('tr');
    totalRow.innerHTML = `
        <td><strong>总计</strong></td>
        <td><strong>${formatCurrency(totalCost)}</strong></td>
        <td><strong>100.00%</strong></td>
    `;
    tbody.appendChild(totalRow);
}

// 添加表格行
function addTableRow(tbody, label, value, total, isBold = false, isSubItem = false) {
    const row = document.createElement('tr');
    // 确保total不为0避免除法错误
    const percentage = total > 0 ? (value / total * 100).toFixed(2) : '0.00';
    
    // 确保值正确格式化
    const formattedValue = formatCurrency(value);
    
    row.innerHTML = `
        <td>${label}</td>
        <td>${formattedValue}</td>
        <td>${percentage}%</td>
    `;
    
    // 设置样式
    if (isBold) {
        // 大类项目：加粗，左对齐
        row.cells[0].style.fontWeight = 'bold';
        row.cells[1].style.fontWeight = 'bold';
        row.cells[2].style.fontWeight = 'bold';
        row.cells[0].style.textAlign = 'left';
    } else if (isSubItem) {
        // 子类项目：右对齐
        row.cells[0].style.textAlign = 'right';
    }
    
    tbody.appendChild(row);
}

// 生成BOM明细表格
function generateBomDetail() {
    const tbody = document.getElementById('bomCostTableBody');
    if (!tbody) return;
    
    // 清空表格
    tbody.innerHTML = '';
    
    let index = 1;
    
    // 塑料件
    if (document.getElementById('plasticDetailedMode').checked) {
        // 分项计算模式
        addBomItemRow(tbody, index++, '外壳', '塑料', '自产',
            document.getElementById('outerShellWeight').value, 
            'g', 
            document.getElementById('outerShellUnitPrice').value, 
            document.getElementById('outerShellCost').value,
            document.getElementById('outerShellCheck').checked,
            '¥/kg'
        );
        
        addBomItemRow(tbody, index++, '高压骨架', '塑料', '自产',
            document.getElementById('highVoltageWeight').value, 
            'g', 
            document.getElementById('highVoltageUnitPrice').value, 
            document.getElementById('highVoltageCost').value,
            document.getElementById('highVoltageCheck').checked,
            '¥/kg'
        );
        
        addBomItemRow(tbody, index++, '低压骨架', '塑料', '自产',
            document.getElementById('lowVoltageWeight').value, 
            'g', 
            document.getElementById('lowVoltageUnitPrice').value, 
            document.getElementById('lowVoltageCost').value,
            document.getElementById('lowVoltageCheck').checked,
            '¥/kg'
        );
        
        if (document.getElementById('customPlasticCheck').checked) {
            addBomItemRow(tbody, index++, 
                document.getElementById('customPlasticName').value || '自定义塑料件', 
                '塑料', 
                '自产',
                document.getElementById('customPlasticWeight').value, 
                'g', 
                document.getElementById('customPlasticUnitPrice').value, 
                document.getElementById('customPlasticCost').value,
                true,
                '¥/kg'
            );
        }
    } else {
        // 整体采购模式
        addBomItemRow(tbody, index++, '塑料件组件', 
            document.getElementById('plasticBulkSpec').value || '整体采购', 
            document.getElementById('plasticBulkSupplier').value,
            1, '套', 
            document.getElementById('plasticBulkPrice').value, 
            document.getElementById('plasticBulkPrice').value,
            true,
            '¥/套'
        );
    }
    
    // 铜线
    addBomItemRow(tbody, index++, '高压铜线', '铜线', '',
        document.getElementById('highVoltageWireWeight').value, 
        'g', 
        document.getElementById('highVoltageWireUnitPrice').value, 
        document.getElementById('highVoltageWireCost').value,
        document.getElementById('highVoltageWireCheck').checked,
        '¥/kg'
    );
    
    addBomItemRow(tbody, index++, '低压铜线', '铜线', '',
        document.getElementById('lowVoltageWireWeight').value, 
        'g', 
        document.getElementById('lowVoltageWireUnitPrice').value, 
        document.getElementById('lowVoltageWireCost').value,
        document.getElementById('lowVoltageWireCheck').checked,
        '¥/kg'
    );
    
    // 铁芯
    if (document.getElementById('ironCoreCheck').checked) {
        addBomItemRow(tbody, index++, '铁芯', 
            document.getElementById('ironCoreSpec').value || '-',
            document.getElementById('ironCoreSupplier').value,
            1, '个', 
            document.getElementById('ironCorePrice').value, 
            document.getElementById('ironCoreCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('ironSleeveCheck').checked) {
        addBomItemRow(tbody, index++, '铁套', 
            document.getElementById('ironSleeveSpec').value || '-',
            document.getElementById('ironSleeveSupplier').value,
            1, '个', 
            document.getElementById('ironSleevePrice').value, 
            document.getElementById('ironSleeveCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('magnetCheck').checked) {
        addBomItemRow(tbody, index++, '磁铁', 
            document.getElementById('magnetSpec').value || '-',
            document.getElementById('magnetSupplier').value,
            1, '个', 
            document.getElementById('magnetPrice').value, 
            document.getElementById('magnetCost').value,
            true,
            '¥/个'
        );
    }
    
    // 模块
    if (document.getElementById('moduleCheck').checked) {
        addBomItemRow(tbody, index++, '点火模块', 
            document.getElementById('moduleSpec').value || '-',
            document.getElementById('moduleSupplier').value,
            1, '个', 
            document.getElementById('modulePrice').value, 
            document.getElementById('moduleCost').value,
            true,
            '¥/个'
        );
    }
    
    // 配件
    if (document.getElementById('screwCheck').checked) {
        addBomItemRow(tbody, index++, '螺丝', 
            document.getElementById('screwSpec').value || '-',
            document.getElementById('screwSupplier').value,
            document.getElementById('screwQuantity').value, 
            '个', 
            document.getElementById('screwUnitPrice').value, 
            document.getElementById('screwCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('nutCheck').checked) {
        addBomItemRow(tbody, index++, '螺帽', 
            document.getElementById('nutSpec').value || '-',
            document.getElementById('nutSupplier').value,
            document.getElementById('nutQuantity').value, 
            '个', 
            document.getElementById('nutUnitPrice').value, 
            document.getElementById('nutCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('hvRodCheck').checked) {
        addBomItemRow(tbody, index++, '高压杆', 
            document.getElementById('hvRodSpec').value || '-',
            document.getElementById('hvRodSupplier').value,
            document.getElementById('hvRodQuantity').value, 
            '个', 
            document.getElementById('hvRodUnitPrice').value, 
            document.getElementById('hvRodCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('rubberCheck').checked) {
        addBomItemRow(tbody, index++, '橡胶件', 
            document.getElementById('rubberSpec').value || '-',
            document.getElementById('rubberSupplier').value,
            document.getElementById('rubberQuantity').value, 
            '个', 
            document.getElementById('rubberUnitPrice').value, 
            document.getElementById('rubberCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('siliconePadCheck').checked) {
        addBomItemRow(tbody, index++, '硅胶垫片', 
            document.getElementById('siliconePadSpec').value || '-',
            document.getElementById('siliconePadSupplier').value,
            document.getElementById('siliconePadQuantity').value, 
            '个', 
            document.getElementById('siliconePadUnitPrice').value, 
            document.getElementById('siliconePadCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('customPartCheck').checked) {
        addBomItemRow(tbody, index++, 
            document.getElementById('customPartName').value || '自定义配件', 
            document.getElementById('customPartSpec').value || '-',
            document.getElementById('customPartSupplier').value,
            document.getElementById('customPartQuantity').value, 
            '个', 
            document.getElementById('customPartUnitPrice').value, 
            document.getElementById('customPartCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('customPart2Check').checked) {
        addBomItemRow(tbody, index++, 
            document.getElementById('customPart2Name').value || '自定义配件2', 
            document.getElementById('customPart2Spec').value || '-',
            document.getElementById('customPart2Supplier').value,
            document.getElementById('customPart2Quantity').value, 
            '个', 
            document.getElementById('customPart2UnitPrice').value, 
            document.getElementById('customPart2Cost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('customPart3Check').checked) {
        addBomItemRow(tbody, index++, 
            document.getElementById('customPart3Name').value || '自定义配件3', 
            document.getElementById('customPart3Spec').value || '-',
            document.getElementById('customPart3Supplier').value,
            document.getElementById('customPart3Quantity').value, 
            '个', 
            document.getElementById('customPart3UnitPrice').value, 
            document.getElementById('customPart3Cost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('customPart4Check').checked) {
        addBomItemRow(tbody, index++, 
            document.getElementById('customPart4Name').value || '自定义配件4', 
            document.getElementById('customPart4Spec').value || '-',
            document.getElementById('customPart4Supplier').value,
            document.getElementById('customPart4Quantity').value, 
            '个', 
            document.getElementById('customPart4UnitPrice').value, 
            document.getElementById('customPart4Cost').value,
            true,
            '¥/个'
        );
    }
    
    // 环氧树脂
    addBomItemRow(tbody, index++, '环氧树脂', '树脂',
        document.getElementById('resinSupplier').value,
        document.getElementById('resinWeight').value, 
        'g', 
        document.getElementById('resinUnitPrice').value, 
        document.getElementById('resinTotal').value,
        true,
        '¥/kg'
    );
    
    // 包装
    if (document.getElementById('bubbleBagCheck').checked) {
        addBomItemRow(tbody, index++, '气泡袋', 
            document.getElementById('bubbleBagSpec').value || '-',
            '', // 包装暂时不需要供应商
            1, '个', 
            document.getElementById('bubbleBagPrice').value, 
            document.getElementById('bubbleBagCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('innerBoxCheck').checked) {
        addBomItemRow(tbody, index++, '内盒', 
            document.getElementById('innerBoxSpec').value || '-',
            '', // 包装暂时不需要供应商
            1, '个', 
            document.getElementById('innerBoxPrice').value, 
            document.getElementById('innerBoxCost').value,
            true,
            '¥/个'
        );
    }
    
    if (document.getElementById('outerBoxCheck').checked) {
        const quantityPerBox = parseFloat(document.getElementById('quantityPerBox').value) || 1;
        addBomItemRow(tbody, index++, '外箱', 
            document.getElementById('outerBoxSpec').value || '-',
            '', // 包装暂时不需要供应商
            1/quantityPerBox, '个', 
            document.getElementById('outerBoxPrice').value, 
            document.getElementById('outerBoxCost').value,
            true,
            '¥/个'
        );
    }
    
    // 添加BOM总计行
    const totalRow = document.createElement('tr');
    totalRow.innerHTML = `
        <td></td>
        <td></td>
        <td></td>
        <td style="text-align: right;"><strong>BOM成本总计：</strong></td>
        <td style="text-align: right;"><strong>${formatCurrency(document.getElementById('bomTotal').value)}</strong></td>
        <td></td>
        <td></td>
    `;
    tbody.appendChild(totalRow);
    
    // 添加运输成本
    if (transportationTotal > 0) {
        let transportLabel = '运输成本';
        let transportSpec = '';
        
        if (document.getElementById('transportDetailedMode').checked) {
            const destination = document.getElementById('destination').value;
            if (destination) {
                transportLabel = '运输成本';
                transportSpec = destination;
            }
        }
        
        // 单个产品的运输成本
        addBomItemRow(
            tbody,
            index++,
            transportLabel,
            transportSpec,
            '', // 运输成本没有供应商
            1,
            '个',
            transportationTotal,
            transportationTotal,
            true
        );
    }
}

// 添加BOM明细行
function addBomItemRow(tbody, index, name, spec, supplier, quantity, unit, unitPrice, totalPrice, isActive, unitSymbol = '') {
    if (!isActive) return;
    
    quantity = parseFloat(quantity) || 0;
    unitPrice = parseFloat(unitPrice) || 0;
    totalPrice = parseFloat(totalPrice) || 0;
    
    if (quantity === 0 && totalPrice === 0) return;
    
    const row = document.createElement('tr');
    
    // 显示单价时添加单位标识
    let formattedUnitPrice;
    if (unitSymbol) {
        // 特殊处理不同材料的单位显示
        if (unitSymbol === '¥/kg') {
            formattedUnitPrice = `${formatCurrency(unitPrice).replace(' ¥', '')} ¥/kg`;
        } else if (unitSymbol === '¥/套') {
            formattedUnitPrice = `${formatCurrency(unitPrice).replace(' ¥', '')} ¥/套`;
        } else {
            formattedUnitPrice = `${formatCurrency(unitPrice)} ${unitSymbol.replace('¥/', '')}`;
        }
    } else {
        formattedUnitPrice = formatCurrency(unitPrice);
    }
    
    row.innerHTML = `
        <td>${index}</td>
        <td>${name}</td>
        <td>${quantity} ${unit}</td>
        <td style="text-align: right;">${formattedUnitPrice}</td>
        <td style="text-align: right;">${formatCurrency(totalPrice)}</td>
        <td>${supplier || '-'}</td>
        <td>${spec}</td>
    `;
    
    tbody.appendChild(row);
}

// 生成人工明细表格
function generateLaborDetail() {
    const tbody = document.getElementById('laborCostTableBody');
    if (!tbody) return;
    
    // 清空表格
    tbody.innerHTML = '';
    
    // 检查人工成本计算方式
    if (document.getElementById('laborDetailedMode').checked) {
        // 分项计算模式
        const hourlyRate = parseFloat(document.getElementById('hourlyRate').value) || 0;
        
        // 按照DOM中的实际顺序获取工序（拖拽后的顺序）
        const laborContainer = document.getElementById('laborProcessContainer');
        const draggableCards = laborContainer.querySelectorAll('.draggable-card');
        
        draggableCards.forEach(card => {
            const processType = card.getAttribute('data-process');
            
            // 处理预定义工序
            const processMap = {
                'injectionProcess': {check: 'injectionProcess', hours: 'injectionHours', label: '注塑'},
                'highVoltageWindingProcess': {check: 'highVoltageWindingProcess', hours: 'highVoltageWindingHours', label: '高压绕线'},
                'lowVoltageWindingProcess': {check: 'lowVoltageWindingProcess', hours: 'lowVoltageWindingHours', label: '低压绕线'},
                'tinningProcess': {check: 'tinningProcess', hours: 'tinningHours', label: '上锡'},
                'weldingProcess': {check: 'weldingProcess', hours: 'weldingHours', label: '焊接'},
                'inspectionProcess': {check: 'inspectionProcess', hours: 'inspectionHours', label: '检测'},
                'potProcess': {check: 'potProcess', hours: 'potHours', label: '灌胶'},
                'assemblyProcess': {check: 'assemblyProcess', hours: 'assemblyHours', label: '组装'},
                'testingProcess': {check: 'testingProcess', hours: 'testingHours', label: '测试'},
                'packagingProcess': {check: 'packagingProcess', hours: 'packagingHours', label: '包装'}
            };
            
            if (processMap[processType]) {
                const process = processMap[processType];
                if (document.getElementById(process.check).checked) {
                    const hours = parseFloat(document.getElementById(process.hours).value) || 0;
                    if (hours > 0) {
                        const cost = (hours * hourlyRate) / 1000;
                        addLaborRow(tbody, process.label, hours, hourlyRate, cost);
                    }
                }
            }
            // 处理自定义工序
            else if (processType && processType.startsWith('customProcess')) {
                const customIndex = processType.replace('customProcess', '');
                const checkId = `customProcess${customIndex}`;
                const nameId = `customProcess${customIndex}Name`;
                const hoursId = `customProcess${customIndex}Hours`;
                
                if (document.getElementById(checkId).checked) {
                    const name = document.getElementById(nameId).value || `自定义工序${customIndex}`;
                    const hours = parseFloat(document.getElementById(hoursId).value) || 0;
                    if (hours > 0) {
                        const cost = (hours * hourlyRate) / 1000;
                        addLaborRow(tbody, name, hours, hourlyRate, cost);
                    }
                }
            }
        });
    } else {
        // 整体输入模式
        const bulkCost = parseFloat(document.getElementById('laborBulkPrice').value) || 0;
        if (bulkCost > 0) {
            addLaborRow(tbody, '人工总成本', '-', 0, bulkCost);
        }
    }
    
    // 添加总计行
    const totalRow = document.createElement('tr');
    totalRow.innerHTML = `
        <td><strong>总计</strong></td>
        <td></td>
        <td></td>
        <td><strong>${formatCurrency(document.getElementById('laborTotal').value)}</strong></td>
    `;
    tbody.appendChild(totalRow);
}

// 添加人工明细行
function addLaborRow(tbody, name, hours, hourlyRate, cost) {
    const row = document.createElement('tr');
    row.innerHTML = `
        <td>${name}</td>
        <td>${hours}</td>
        <td>${hourlyRate.toFixed(2)} ¥/小时</td>
        <td>${formatCurrency(cost)}</td>
    `;
    
    tbody.appendChild(row);
}

// 格式化货币
function formatCurrency(value) {
    const num = parseFloat(value) || 0;
    return num.toFixed(2) + ' ¥';
}

// 导出Excel
function exportToExcel() {
    // 确保已经计算并生成了成本明细
    calculateTotalCost();
    generateCostDetail();
    
    const oeNumber = document.getElementById('oeNumber').value || '无OE号';
    const internalNumber = document.getElementById('internalNumber').value || '无内部编号';
    const wb = new ExcelJS.Workbook();
    
    // 产品信息工作表
    const productInfoWS = wb.addWorksheet('产品信息');
    productInfoWS.columns = [
        { header: '项目', key: 'item', width: 20 },
        { header: '内容', key: 'content', width: 40 }
    ];
    
    // 设置表头样式
    const headerRow = productInfoWS.getRow(1);
    headerRow.font = { bold: true };
    headerRow.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE8F7E8' }  // 淡绿色背景
    };
    
    // 添加产品基本信息
    productInfoWS.addRow({ item: 'OE号', content: oeNumber });
    productInfoWS.addRow({ item: '公司内部编号', content: internalNumber });
    productInfoWS.addRow({ item: '计算日期', content: new Date().toLocaleString() });
    productInfoWS.addRow({ item: '总成本', content: document.getElementById('totalCost').value });
    
    // 应用样式
    for (let i = 2; i <= 4; i++) {
        const row = productInfoWS.getRow(i);
        row.getCell(1).font = { bold: true };
        
        // 为总成本行设置货币格式
        if (i === 4) {
            row.getCell(2).numFmt = '¥#,##0.00';
        }
    }
    
    // 添加产品图片
    const imagePreview = document.getElementById('imagePreview');
    const imageElements = imagePreview.querySelectorAll('img');
    
    if (imageElements && imageElements.length > 0) {
    // 添加图片标题行
        const imageRow = productInfoWS.addRow({ item: '产品图片', content: '' });
        imageRow.getCell(1).font = { bold: true };
    
        // 设置较大的行高来容纳图片
        productInfoWS.getRow(imageRow.number).height = 150;
    
        // 遍历所有图片并添加到Excel
        let imageIndex = 0;
        Array.from(imageElements).forEach(img => {
            try {
                // 获取图片的base64数据
                const imageData = img.src;
                
                if (imageData && imageData.startsWith('data:image')) {
                    // 提取base64编码的图像数据（去掉data:image/jpeg;base64,前缀）
                    const base64Data = imageData.split(',')[1];
                    
                    // 添加图片到工作表
                    const imageId = wb.addImage({
                        base64: base64Data,
                        extension: 'png',
                    });
                    
                    // 根据图片索引确定位置
                    const colOffset = imageIndex % 2; // 每行最多2张图片
                    const rowOffset = Math.floor(imageIndex / 2); // 每2张图片换行
                    
                    // 将图片添加到单元格，并设置其大小
                    productInfoWS.addImage(imageId, {
                        tl: { col: 1 + colOffset, row: imageRow.number + rowOffset * 10 },
                        ext: { width: 150, height: 150 }
                    });
                    
                    imageIndex++;
                }
            } catch (error) {
                console.error('添加图片失败:', error);
                }
            });
    }
    
    // 获取成本汇总明细表格数据
    const costSummaryTable = document.getElementById('costSummaryTable');
    const costSummaryWS = wb.addWorksheet('成本汇总明细');
    addTableDataToWorksheet(costSummaryTable, costSummaryWS, '成本汇总明细');
    
    // 获取BOM成本表格数据
    const bomCostTable = document.getElementById('bomCostTable');
    const bomCostWS = wb.addWorksheet('BOM成本明细');
    addTableDataToWorksheet(bomCostTable, bomCostWS, 'BOM成本明细');
    
    // 获取人工成本明细表格数据
    const laborCostTable = document.getElementById('laborCostTable');
    const laborCostWS = wb.addWorksheet('人工成本明细');
    addTableDataToWorksheet(laborCostTable, laborCostWS, '人工成本明细');
    
    // 设置列宽
    const costSummaryColumnWidths = [
       { width: 40 }, // 成本项目/名称列
       { width: 15 }, // 金额/数量列
       { width: 15 }  // 占比列
    ];
    
    const bomColumnWidths = [
       { width: 12 },  // 序号列（加宽）
       { width: 25 }, // 物料名称列
       { width: 12 }, // 数量列
       { width: 15 }, // 单价列
       { width: 15 }, // 总价列
       { width: 20 }, // 供应商列
       { width: 15 }  // 规格列
    ];
    
    const laborColumnWidths = [
       { width: 30 }, // 工序名称列
       { width: 25 }, // 1000个产品工时列（加宽）
       { width: 25 }, // 大工工价列
       { width: 20 }  // 单个产品人工成本列
    ];
    
    // 为其他工作表设置列宽
    costSummaryWS.columns = costSummaryColumnWidths;
    bomCostWS.columns = bomColumnWidths;
    laborCostWS.columns = laborColumnWidths;
    
    // 添加样式
    applyStyles(costSummaryWS);
    applyStyles(bomCostWS);
    applyStyles(laborCostWS);
    
    // 导出为Excel文件，文件名包含OE号和内部编号
    try {
        wb.xlsx.writeBuffer().then(function(buffer) {
            saveAs(new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 
                   `点火线圈成本核算_${oeNumber}_${internalNumber}.xlsx`);
        }).catch(function(error) {
            console.error('Excel生成过程中出错:', error);
            alert('导出Excel时发生错误，请查看控制台获取详细信息');
        });
    } catch (e) {
        console.error('Excel导出总体错误:', e);
        alert('导出Excel失败，请重试或联系开发人员');
    }
}

// 添加表格数据到工作表并应用样式
function addTableDataToWorksheet(table, worksheet, tableName) {
    if (!table) return;
    
    const rows = table.rows;
    
    // 获取表头行并创建自定义表头
    const headerRow = rows[0];
    if (headerRow) {
        const headerCells = headerRow.cells;
        const headerData = [];
        
        for (let j = 0; j < headerCells.length; j++) {
            let headerText = headerCells[j].textContent.trim();
            
            // 根据索引为特定列设置特定表头名称
            if (headerCells.length >= 3) {
                // 针对成本汇总明细表格
                if (tableName === '成本汇总明细' && j === 1) {
                    headerText = '金额(¥)';
                } else if (tableName === '成本汇总明细' && j === 2) {
                    headerText = '占比(%)';
                }
                // 针对BOM成本明细表格
                else if (tableName === 'BOM成本明细' && j === 3) {
                    headerText = '单价(¥)';
                } else if (tableName === 'BOM成本明细' && j === 4) {
                    headerText = '总价(¥)';
                }
                // 针对人工成本明细表格
                else if (tableName === '人工成本明细' && j === 1) {
                    headerText = '1000个产品工时(小时)';
                } else if (tableName === '人工成本明细' && j === 2) {
                    headerText = '大工工价(¥/小时，含社保)';
                } else if (tableName === '人工成本明细' && j === 3) {
                    headerText = '单个产品人工成本(¥)';
                }
            }
            
            headerData.push(headerText);
        }
        
        // 添加自定义表头行
        const excelHeaderRow = worksheet.addRow(headerData);
        
        // 设置表头样式
        excelHeaderRow.eachCell(cell => {
            cell.font = { bold: true };
            cell.fill = {
                type: 'pattern',
                pattern: 'solid',
                fgColor: { argb: 'FFE8F7E8' }  // 淡绿色背景
            };
            cell.alignment = { vertical: 'middle', horizontal: 'center' };
        });
    }
    
    // 处理数据行
    for (let i = 1; i < rows.length; i++) {
        const rowData = [];
        const cells = rows[i].cells;
        
        // 收集所有单元格的数据
        for (let j = 0; j < cells.length; j++) {
            const cellText = cells[j].textContent.trim();
            
            // 根据不同类型处理数据
            if (cellText.includes('¥') && !cellText.includes('/')) {
                // 纯金额格式（不包含单位后缀如¥/kg）
                const valueStr = cellText.replace(/[¥,\s]/g, '');
                const value = parseFloat(valueStr) || 0; // 使用0代替NaN
                rowData.push(value);
            } else if (cellText.includes('%')) {
                // 百分比格式
                const valueStr = cellText.replace(/[%\s]/g, '');
                const value = parseFloat(valueStr) / 100 || 0; // 使用0代替NaN
                rowData.push(value);
            } else {
                // 普通文本（包括带单位的价格如"120.00 ¥/kg"）
                rowData.push(cellText);
            }
        }
        
        // 添加行
        const row = worksheet.addRow(rowData);
        
        // 设置货币和百分比格式以及对齐
        for (let j = 0; j < cells.length; j++) {
            const cellText = cells[j].textContent.trim();
            const cell = row.getCell(j + 1);
            
            if (cellText.includes('¥') && !cellText.includes('/')) {
                // 只对纯金额格式应用货币格式
                cell.numFmt = '¥#,##0.00';
                cell.alignment = { horizontal: 'right', vertical: 'middle' };
            } else if (cellText.includes('%')) {
                cell.numFmt = '0.00%';
            } else if (cellText.includes('¥/')) {
                // 带单位的价格（如"120.00 ¥/kg"）右对齐
                cell.alignment = { horizontal: 'right', vertical: 'middle' };
            }
            
            // 为BOM明细表的单价和总价列设置右对齐
            if (tableName === 'BOM成本明细') {
                if (j === 3 || j === 4) { // 单价列和总价列
                    cell.alignment = { horizontal: 'right', vertical: 'middle' };
                }
            }
        }
        
        // 检查是否为标题行或总计行
        const firstCellText = cells[0].textContent.trim();
        
        // 检查是否为总计行
        const isTotal = cellText => 
            cellText === '总计' || 
            cellText.includes('总计') || 
            cellText.includes('BOM成本总计') || 
            cellText.includes('人工成本总计');
            
        // 检查是否为需要加粗的标题行（成本汇总明细表中的大类标题）
        const isBoldHeader = cellText =>
            tableName === '成本汇总明细' && (
                cellText.includes('BOM物料成本') ||
                cellText.includes('人工成本') ||
                cellText.includes('管理费') ||
                cellText.includes('运输成本') ||
                cellText.includes('水电费及设备折旧费')
            );
            
        // 设置总计行或标题行样式
        if (isTotal(firstCellText) || 
            (cells.length > 1 && isTotal(cells[1].textContent.trim())) ||
            (cells.length > 3 && isTotal(cells[3].textContent.trim())) ||
            isBoldHeader(firstCellText)) {
            row.eachCell(cell => {
                if (!cell.font) cell.font = {};
                cell.font = { bold: true };
            });
        }
        
        // 成本汇总明细表：小条目右对齐（不包含数字编号开头的大标题和总计）
        if (tableName === '成本汇总明细') {
            const isMainTitle = /^\d+\./.test(firstCellText) || firstCellText.includes('总计');
            if (!isMainTitle && firstCellText.trim() !== '' && firstCellText !== '成本项目') {
                const firstCell = row.getCell(1);
                firstCell.alignment = { horizontal: 'right', vertical: 'middle' };
            }
        }
    }
}

// 应用样式到工作表
function applyStyles(worksheet) {
    // 确保表头加粗 - 现在这不是必要的，因为我们在addTableDataToWorksheet中已经设置了表头样式
    
    // 遍历所有行，确保总计行加粗
    worksheet.eachRow((row, rowNumber) => {
        // 跳过表头
        if (rowNumber === 1) return;
        
        // 处理每一行的第一个单元格
        const firstCell = row.getCell(1);
        if (!firstCell || !firstCell.value) return;
        
        // 如果是"总计"行或包含"总计"字样，加粗整行
        const cellValue = firstCell.value.toString();
        if (cellValue.includes('总计') || cellValue.includes('BOM成本总计') || cellValue.includes('人工成本总计')) {
            row.eachCell(cell => {
                if (!cell.font) cell.font = {};
                cell.font = { bold: true };
            });
        }
    });
}

// 重置表单
function resetForm() {
    if (confirm('确定要重置所有数据吗？')) {
        location.reload();
    }
    
    // 重置大工工价
    document.getElementById('hourlyRate').value = 0;
    
    // 重置人工工序工时字段
    const laborHoursFields = [
        'injectionHours', 'highVoltageWindingHours', 'lowVoltageWindingHours',
        'tinningHours', 'weldingHours', 'inspectionHours', 'potHours',
        'assemblyHours', 'testingHours', 'packagingHours',
        'customProcess1Hours', 'customProcess2Hours', 'customProcess3Hours',
        'customProcess4Hours', 'customProcess5Hours'
    ];
    
    laborHoursFields.forEach(fieldId => {
        const element = document.getElementById(fieldId);
        if (element) {
            element.value = 0;
        }
    });
    
    // 重置运输计算表单
    document.getElementById('transportDetailedMode').checked = false;
    document.getElementById('transportBulkMode').checked = true;
    document.getElementById('transportDetailedSection').style.display = 'none';
    document.getElementById('transportBulkSection').style.display = 'block';
    
    document.getElementById('productQuantity').value = 1;
    document.getElementById('productWeight').value = 0;
    document.getElementById('destination').value = '';
    document.getElementById('transportationCost').value = 0;
    
    // 重置硅胶垫片 - 默认不勾选
    document.getElementById('siliconePadCheck').checked = false;
    document.getElementById('siliconePadQuantity').value = 1;
    document.getElementById('siliconePadUnitPrice').value = 0.022;
    document.getElementById('siliconePadCost').value = 0.022;
    document.getElementById('siliconePadCostDisplay').textContent = '0.02 ¥';
    document.getElementById('siliconePadForm').style.display = 'none';
    
    // 重置铁芯相关字段
    document.getElementById('ironCoreCheck').checked = false;
    document.getElementById('ironCoreForm').style.display = 'none';
    document.getElementById('ironCorePrice').value = 0;
    document.getElementById('ironCoreSpec').value = '';
    document.getElementById('ironCoreCost').value = 0;
    document.getElementById('ironCoreCostDisplay').textContent = '0.00 ¥';
    
    document.getElementById('ironSleeveCheck').checked = false;
    document.getElementById('ironSleeveForm').style.display = 'none';
    document.getElementById('ironSleevePrice').value = 0;
    document.getElementById('ironSleeveSpec').value = '';
    document.getElementById('ironSleeveCost').value = 0;
    document.getElementById('ironSleeveCostDisplay').textContent = '0.00 ¥';
    
    document.getElementById('magnetCheck').checked = false;
    document.getElementById('magnetForm').style.display = 'none';
    document.getElementById('magnetPrice').value = 0;
    document.getElementById('magnetSpec').value = '';
    document.getElementById('magnetCost').value = 0;
    document.getElementById('magnetCostDisplay').textContent = '0.00 ¥';
    
    resetShippingCalculation();
    
    // 重置塑料件相关字段
    document.getElementById('plasticBulkPrice').value = 0;
    document.getElementById('plasticBulkSpec').value = '';
    document.getElementById('plasticBulkSupplier').value = '';
    
    // 重置水电费及设备折旧费
    document.getElementById('utilitiesAndDepreciation').value = 0;
    document.getElementById('utilitiesAndDepreciationTotal').value = 0;
    document.getElementById('utilitiesAndDepreciationTotalDisplay').textContent = '0.00 ¥';
    
    // 重置管理费
    document.getElementById('managementCost').value = 0;
    document.getElementById('managementTotal').value = 0;
    document.getElementById('managementTotalDisplay').textContent = '0.00 ¥';
    
    // 重置供应商字段
    const supplierFields = [
        'ironCoreSupplier', 'ironSleeveSupplier', 'magnetSupplier', 'moduleSupplier',
        'screwSupplier', 'nutSupplier', 'hvRodSupplier', 'rubberSupplier', 'siliconePadSupplier',
        'customPartSupplier', 'customPart2Supplier', 'customPart3Supplier', 'customPart4Supplier',
        'resinSupplier'
    ];
    
    supplierFields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field) {
            field.value = '';
        }
    });
}

// 初始化铜线计算相关事件
function initWireCalculation() {
    console.log('初始化铜线计算功能');

    // 铜价基础价格变更事件
    const copperBasePrice = document.getElementById('copperBasePrice');
    if (copperBasePrice) {
        copperBasePrice.addEventListener('input', function() {
            // 当基础铜价变化时，更新按钮状态
            updateCopperBasePriceState();
            console.log('铜基础价格已更新:', this.value);
        });
    }
    
    // 高压铜线计算事件
    const calculateHighVoltageWirePrice = document.getElementById('calculateHighVoltageWirePrice');
    if (calculateHighVoltageWirePrice) {
        calculateHighVoltageWirePrice.addEventListener('click', function() {
            console.log('高压铜线计算按钮点击');
            calculateCopperWirePrice('highVoltage');
        });
    }
    
    // 低压铜线计算事件
    const calculateLowVoltageWirePrice = document.getElementById('calculateLowVoltageWirePrice');
    if (calculateLowVoltageWirePrice) {
        calculateLowVoltageWirePrice.addEventListener('click', function() {
            console.log('低压铜线计算按钮点击');
            calculateCopperWirePrice('lowVoltage');
        });
    }
    
    // 高压和低压铜线直径和加工费输入事件
    const highVoltageDiameter = document.getElementById('highVoltageWireDiameter');
    const highVoltageProcessingFee = document.getElementById('highVoltageWireProcessingFee');
    const lowVoltageDiameter = document.getElementById('lowVoltageWireDiameter');
    const lowVoltageProcessingFee = document.getElementById('lowVoltageWireProcessingFee');
    
    if (highVoltageDiameter && highVoltageProcessingFee) {
        highVoltageDiameter.addEventListener('input', function() {
            // 尝试根据直径自动填充加工费
            const fee = getProcessingFeeByDiameter(this.value);
            if (fee > 0) {
                highVoltageProcessingFee.value = fee;
            }
        });
    }
    
    if (lowVoltageDiameter && lowVoltageProcessingFee) {
        lowVoltageDiameter.addEventListener('input', function() {
            // 尝试根据直径自动填充加工费
            const fee = getProcessingFeeByDiameter(this.value);
            if (fee > 0) {
                lowVoltageProcessingFee.value = fee;
            }
        });
    }

    // 初始化铜线单价输入事件
    const highVoltageWireUnitPrice = document.getElementById('highVoltageWireUnitPrice');
    const lowVoltageWireUnitPrice = document.getElementById('lowVoltageWireUnitPrice');
    
    if (highVoltageWireUnitPrice) {
        highVoltageWireUnitPrice.addEventListener('input', function() {
            calculateWireCost('highVoltage');
        });
    }
    
    if (lowVoltageWireUnitPrice) {
        lowVoltageWireUnitPrice.addEventListener('input', function() {
            calculateWireCost('lowVoltage');
        });
    }

    // 重量输入事件
    const highVoltageWireWeight = document.getElementById('highVoltageWireWeight');
    const lowVoltageWireWeight = document.getElementById('lowVoltageWireWeight');
    
    if (highVoltageWireWeight) {
        highVoltageWireWeight.addEventListener('input', function() {
            calculateWireCost('highVoltage');
        });
    }
    
    if (lowVoltageWireWeight) {
        lowVoltageWireWeight.addEventListener('input', function() {
            calculateWireCost('lowVoltage');
        });
    }
    
    // 初始化时调用一次更新状态
    updateCopperBasePriceState();
}

// 检查并更新铜价基础价格状态
function updateCopperBasePriceState() {
    const copperBasePrice = document.getElementById('copperBasePrice');
    const calculateHighVoltageWirePrice = document.getElementById('calculateHighVoltageWirePrice');
    const calculateLowVoltageWirePrice = document.getElementById('calculateLowVoltageWirePrice');
    
    if (copperBasePrice && calculateHighVoltageWirePrice && calculateLowVoltageWirePrice) {
        const basePrice = parseFloat(copperBasePrice.value) || 0;
        
        // 如果基础铜价为0，禁用自动计算按钮
        calculateHighVoltageWirePrice.disabled = basePrice <= 0;
        calculateLowVoltageWirePrice.disabled = basePrice <= 0;
        
        if (basePrice <= 0) {
            calculateHighVoltageWirePrice.title = "请先输入有效的铜基础价格";
            calculateLowVoltageWirePrice.title = "请先输入有效的铜基础价格";
        } else {
            calculateHighVoltageWirePrice.title = "";
            calculateLowVoltageWirePrice.title = "";
        }
    }
}

// 根据铜线直径查询加工费
function getProcessingFeeByDiameter(diameter) {
    // 将直径转换为数字并保留3位小数
    diameter = parseFloat(parseFloat(diameter).toFixed(3));
    
    // 加工费参考表（加工费单位：元/kg）
    const processingFees = [
        { diameter: 0.040, fee: 40.00 },
        { diameter: 0.045, fee: 30.00 },
        { diameter: 0.048, fee: 22.00 },  // 处理范围
        { diameter: 0.050, fee: 22.00 },  // 处理范围
        { diameter: 0.055, fee: 20.00 },
        { diameter: 0.060, fee: 18.00 },
        { diameter: 0.065, fee: 17.00 },
        { diameter: 0.070, fee: 16.00 },
        { diameter: 0.080, fee: 14.00 },
        { diameter: 0.090, fee: 13.00 }
    ];
    
    // 精确匹配
    const exactMatch = processingFees.find(item => item.diameter === diameter);
    if (exactMatch) {
        return exactMatch.fee;
    }
    
    // 范围匹配（针对0.048-0.050的情况）
    if (diameter >= 0.048 && diameter <= 0.050) {
        return 22.00;
    }
    
    // 如果没有精确匹配，返回0让用户手动输入
    return 0;
}

// 计算铜线单价（基础铜价+加工费）
function calculateCopperWirePrice(type) {
    console.log('计算铜线单价:', type);
    const basePrice = parseFloat(document.getElementById('copperBasePrice').value) || 0;
    const processingFeeInput = document.getElementById(`${type}WireProcessingFee`);
    const unitPriceInput = document.getElementById(`${type}WireUnitPrice`);
    
    if (!basePrice) {
        alert('请先输入铜基础价格');
        return;
    }
    
    const processingFee = parseFloat(processingFeeInput.value) || 0;
    if (!processingFee) {
        alert('请输入加工费');
        return;
    }
    
    // 计算单价（基础铜价 + 加工费）- 加工费已经是元/kg单位了
    const finalPrice = basePrice + processingFee;
    console.log('计算结果:', basePrice, '+', processingFee, '=', finalPrice);
    unitPriceInput.value = finalPrice.toFixed(2);
    
    // 计算总成本
    calculateWireCost(type);
    
    // 高亮显示更新的字段
    animateValueChange(`${type}WireUnitPrice`);
}

// 计算单个铜线的成本
function calculateWireCost(type) {
    const weightInput = document.getElementById(`${type}WireWeight`);
    const unitPriceInput = document.getElementById(`${type}WireUnitPrice`);
    const costInput = document.getElementById(`${type}WireCost`);
    const costDisplay = document.getElementById(`${type}WireCostDisplay`);
    
    if (weightInput && unitPriceInput && costInput && costDisplay) {
        const weight = parseFloat(weightInput.value) || 0;
        const unitPrice = parseFloat(unitPriceInput.value) || 0;
        
        // 计算成本 (g转为kg)
        const cost = (weight / 1000) * unitPrice;
        
        costInput.value = cost.toFixed(2);
        costDisplay.textContent = formatCurrency(cost);
        
        // 更新总成本
        calculateWireTotal();
    }
}

// 计算铜线总成本
function calculateWireTotal() {
    const wireTotalInput = document.getElementById('wireTotal');
    const wireTotalDisplay = document.getElementById('wireTotalDisplay');
    
    let totalCost = 0;
    
    // 分项计算模式
    const highVoltageCheck = document.getElementById('highVoltageWireCheck');
    const lowVoltageCheck = document.getElementById('lowVoltageWireCheck');
    
    if (highVoltageCheck && highVoltageCheck.checked) {
        totalCost += parseFloat(document.getElementById('highVoltageWireCost').value) || 0;
    }
    
    if (lowVoltageCheck && lowVoltageCheck.checked) {
        totalCost += parseFloat(document.getElementById('lowVoltageWireCost').value) || 0;
    }
    
    wireTotalInput.value = totalCost.toFixed(2);
    wireTotalDisplay.textContent = formatCurrency(totalCost);
    
    // 更新BOM总成本
    calculateBomTotal();
    
    // 高亮显示更新的字段
    animateValueChange('wireTotalDisplay');
} 

// 运输价格数据表
const shippingRateData = [
    {province: "浙江", basePrice: 45, rates: [0.7, 0.65, 0.6]},
    {province: "江苏", basePrice: 45, rates: [0.7, 0.65, 0.6]},
    {province: "上海", basePrice: 45, rates: [0.7, 0.65, 0.6]},
    {province: "安徽", basePrice: 45, rates: [0.9, 0.8, 0.7]},
    {province: "福建", basePrice: 55, rates: [1.2, 1.1, 1]},
    {province: "广东", basePrice: 55, rates: [1.2, 1.1, 1]},
    {province: "广西", basePrice: 65, rates: [1.8, 1.7, 1.6]},
    {province: "海南", basePrice: 75, rates: [2.1, 2, 1.9]},
    {province: "北京", basePrice: 65, rates: [1.6, 1.5, 1.4]},
    {province: "天津", basePrice: 65, rates: [1.6, 1.5, 1.4]},
    {province: "山东", basePrice: 65, rates: [1.2, 1.1, 1]},
    {province: "河北", basePrice: 65, rates: [1.6, 1.5, 1.4]},
    {province: "山西", basePrice: 65, rates: [1.6, 1.5, 1.4]},
    {province: "内蒙", basePrice: 75, rates: [2.1, 2, 1.9]},
    {province: "河南", basePrice: 65, rates: [1.3, 1.2, 1.1]},
    {province: "湖南", basePrice: 65, rates: [1.3, 1.2, 1.1]},
    {province: "湖北", basePrice: 65, rates: [1.2, 1.1, 1]},
    {province: "江西", basePrice: 65, rates: [1.3, 1.2, 1.1]},
    {province: "黑龙江", basePrice: 85, rates: [2.1, 2, 1.9]},
    {province: "吉林", basePrice: 85, rates: [2.1, 2, 1.9]},
    {province: "辽宁", basePrice: 85, rates: [2.1, 2, 1.9]},
    {province: "云南", basePrice: 90, rates: [1.9, 1.8, 1.7]},
    {province: "贵州", basePrice: 90, rates: [1.9, 1.8, 1.7]},
    {province: "四川", basePrice: 90, rates: [1.9, 1.8, 1.7]},
    {province: "重庆", basePrice: 90, rates: [1.9, 1.8, 1.7]},
    {province: "西藏", basePrice: 100, rates: [4, 3.5, 3]},
    {province: "陕西", basePrice: 75, rates: [2, 1.9, 1.8]},
    {province: "甘肃", basePrice: 90, rates: [2.1, 2, 1.9]},
    {province: "宁夏", basePrice: 90, rates: [2.1, 2, 1.9]},
    {province: "青海", basePrice: 90, rates: [2.1, 2, 1.9]},
    {province: "新疆", basePrice: 100, rates: [4, 3.5, 3]}
];

// 初始化运输成本计算相关功能
function initTransportationCalculation() {
    // 填充省份下拉菜单
    const destinationSelect = document.getElementById('destination');
    shippingRateData.forEach(item => {
        const option = document.createElement('option');
        option.value = item.province;
        option.textContent = item.province;
        destinationSelect.appendChild(option);
    });
    
    // 填充运输价格表
    const tableBody = document.getElementById('shippingFeeTableBody');
    shippingRateData.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.province}</td>
            <td>${item.basePrice.toFixed(2)}</td>
            <td>${item.rates[0].toFixed(2)}</td>
            <td>${item.rates[1].toFixed(2)}</td>
            <td>${item.rates[2].toFixed(2)}</td>
        `;
        tableBody.appendChild(row);
    });
    
    // 默认显示直接输入模式
    document.getElementById('transportDetailedSection').style.display = 'none';
    document.getElementById('transportBulkSection').style.display = 'block';
    
    // 添加计算方式切换事件
    document.getElementById('transportDetailedMode').addEventListener('change', function() {
        if (this.checked) {
            document.getElementById('transportDetailedSection').style.display = 'block';
            document.getElementById('transportBulkSection').style.display = 'none';
            calculateShippingFee(); // 触发计算
        }
    });
    
    document.getElementById('transportBulkMode').addEventListener('change', function() {
        if (this.checked) {
            document.getElementById('transportDetailedSection').style.display = 'none';
            document.getElementById('transportBulkSection').style.display = 'block';
            // 使用直接输入的值
            calculateTransportationTotal();
        }
    });
    
    // 添加输入变化事件
    const inputElements = ['productQuantity', 'productWeight', 'destination'];
    inputElements.forEach(id => {
        document.getElementById(id).addEventListener('change', calculateShippingFee);
        document.getElementById(id).addEventListener('input', calculateShippingFee);
    });
    
    document.getElementById('transportationCost').addEventListener('change', calculateTransportationTotal);
    document.getElementById('transportationCost').addEventListener('input', calculateTransportationTotal);
    
    // 水电费及设备折旧费输入事件
    const utilitiesAndDepreciation = document.getElementById('utilitiesAndDepreciation');
    if (utilitiesAndDepreciation) {
        utilitiesAndDepreciation.addEventListener('input', calculateUtilitiesAndDepreciationTotal);
    }
    
    // 管理费输入事件
    const managementCost = document.getElementById('managementCost');
    if (managementCost) {
        managementCost.addEventListener('input', calculateManagementTotal);
    }
}

// 计算运输费用
function calculateShippingFee() {
    const quantity = parseInt(document.getElementById('productQuantity').value) || 0;
    const weight = parseFloat(document.getElementById('productWeight').value) || 0;
    const destination = document.getElementById('destination').value;
    
    // 计算总重量（千克）
    const totalWeight = (quantity * weight) / 1000; // 转换为kg
    
    // 更新总重量显示
    document.getElementById('totalWeightDisplay').textContent = totalWeight.toFixed(2) + ' kg';
    
    // 如果没有选择目的地或重量为0，则不计算
    if (!destination || totalWeight <= 0) {
        resetShippingCalculation();
        return;
    }
    
    // 获取选中省份的运费数据
    const provinceData = shippingRateData.find(item => item.province === destination);
    if (!provinceData) {
        resetShippingCalculation();
        return;
    }
    
    // 根据重量确定价格区间
    let rateIndex;
    let unitPrice;
    
    if (totalWeight <= 500) {
        rateIndex = 0; // 500kg以内
    } else if (totalWeight <= 1000) {
        rateIndex = 1; // 500kg-1000kg
    } else {
        rateIndex = 2; // 1000kg以上
    }
    
    unitPrice = provinceData.rates[rateIndex];
    
    // 计算总运费
    let totalFee = totalWeight * unitPrice;
    
    // 检查是否低于起步价
    if (totalFee < provinceData.basePrice) {
        totalFee = provinceData.basePrice;
        // 如果使用起步价，单价显示为"起步价"
        document.getElementById('shippingUnitPriceDisplay').textContent = '起步价: ' + provinceData.basePrice.toFixed(2) + ' ¥';
    } else {
        document.getElementById('shippingUnitPriceDisplay').textContent = unitPrice.toFixed(2) + ' ¥/kg';
    }
    
    // 计算单个产品运费
    const perProductFee = totalFee / quantity;
    
    // 更新显示
    document.getElementById('totalShippingFeeDisplay').textContent = totalFee.toFixed(2) + ' ¥';
    document.getElementById('perProductShippingFeeDisplay').textContent = perProductFee.toFixed(2) + ' ¥';
    
    // 更新总运输成本 - 使用单个产品运费而不是总运费
    document.getElementById('transportationTotal').value = perProductFee.toFixed(2);
    document.getElementById('transportationTotalDisplay').textContent = perProductFee.toFixed(2) + ' ¥';
    
    // 更新总成本
    calculateTotalCost();
    
    // 添加闪烁效果
    animateValueChange('transportationTotalDisplay');
}

// 重置运输计算显示
function resetShippingCalculation() {
    document.getElementById('totalWeightDisplay').textContent = '0.00 kg';
    document.getElementById('shippingUnitPriceDisplay').textContent = '0.00 ¥/kg';
    document.getElementById('totalShippingFeeDisplay').textContent = '0.00 ¥';
    document.getElementById('perProductShippingFeeDisplay').textContent = '0.00 ¥';
    
    // 更新总运输成本
    document.getElementById('transportationTotal').value = '0.00';
    document.getElementById('transportationTotalDisplay').textContent = '0.00 ¥';
    
    // 更新总成本
    calculateTotalCost();
}

// 计算运输成本 - 直接输入模式
function calculateTransportationTotal() {
    if (document.getElementById('transportBulkMode').checked) {
        // 直接输入模式 - 此模式下直接输入的就是单个产品的运输成本
        const transportationCost = parseFloat(document.getElementById('transportationCost').value) || 0;
        
        // 更新运输成本
        document.getElementById('transportationTotal').value = transportationCost.toFixed(2);
        document.getElementById('transportationTotalDisplay').textContent = transportationCost.toFixed(2) + ' ¥';
        
        // 更新总成本
        calculateTotalCost();
        
        // 添加闪烁效果
        animateValueChange('transportationTotalDisplay');
    } else {
        // 自动计算模式下，由calculateShippingFee函数处理
        calculateShippingFee();
    }
} 